import { CRS, LatLng } from "leaflet";

const WORLD_BBOX = [-180, -90, 180, 90];
const TILE = "https://c.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png";
const DEFAULT_LEVELS = Array.from({length: 19}).fill(0).map((v, i) => i);

export async function downloadTile({
  url, 
  bbox = WORLD_BBOX,
  levels = DEFAULT_LEVELS,
  onProgress = () => {},
} = {}) {
  const [west, south, east, north] = bbox;

  url = getTileUrl(TILE, 0, 0, 0);
  const imgData = await loadTile(url);
  const zip = new JSZip();
  var images = zip.folder("images");
  images.file("0.png", imgData, {binary: true});
  // zip.generateAsync({type:"blob"}).then(function(content) {
  //   saveAs(content, "example.zip");
  // });
}

async function loadTile(url) {
  const res = await fetch(url, {method: "GET"});
  const blob = await res.blob();
  return await new Promise((resolve) => {
    var reader = new FileReader();
    reader.onloadend = function () {
      resolve(reader.result);
    };
    reader.readAsBinaryString(blob);
  });
}

function getTileUrl(tpl, x, y, z) {
  let url = tpl;
  [
    ["z", z],
    ["x", x],
    ["y", y],
  ].forEach(([key, value]) => {
    url = url.replace(`{${key}}`, value + "");
  });

  // 多余的{r}, 直接替换成空字符串
  url = url.replace("{r}", "");

  return url;
}